<template>
  <div class="permissions-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="title-section">
        <h1 class="page-title">
          <el-icon class="title-icon"><Key /></el-icon>
          权限管理
        </h1>
        <p class="page-description">管理系统权限，包括菜单、功能和数据权限的配置</p>
      </div>
      <div class="header-actions">
        <el-button type="warning" @click="refreshUserPermissions">
          <el-icon><Refresh /></el-icon>
          刷新权限
        </el-button>
        <el-button 
          type="danger" 
          :disabled="selectedPermissions.length === 0" 
          v-if="userStore.hasPermission('permission.delete')"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button 
          type="primary" 
          v-if="userStore.hasPermission('permission.create')"
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>
          新增权限
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-header">
        <div class="search-title">
          <el-icon><Search /></el-icon>
          搜索筛选
        </div>
        <div class="search-stats">
          <el-tag type="info" size="small">共 {{ total }} 条记录</el-tag>
        </div>
      </div>
      
      <el-form :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="权限名称" class="form-item">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入权限名称"
            clearable
            prefix-icon="Search"
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>
        
        <el-form-item label="权限编码" class="form-item">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入权限编码"
            clearable
            prefix-icon="Key"
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>

        <el-form-item label="权限状态" class="form-item">
          <el-select 
            v-model="queryParams.status" 
            placeholder="选择状态" 
            clearable 
            @change="handleSearch"
          >
            <el-option label="启用" :value="1">
              <span class="option-item">
                <el-icon><CircleCheck /></el-icon>
                启用
              </span>
            </el-option>
            <el-option label="禁用" :value="0">
              <span class="option-item">
                <el-icon><CircleClose /></el-icon>
                禁用
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item class="form-item">
          <div class="button-group">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <!-- 快速筛选 -->
      <div v-if="quickFilters.length > 0" class="quick-filters">
        <span class="filter-label">快速筛选：</span>
        <div class="filter-tags">
          <el-tag
            v-for="filter in quickFilters"
            :key="filter.key"
            :type="filter.type"
            closable
            @close="removeQuickFilter(filter.key)"
          >
            {{ filter.label }}
          </el-tag>
          <el-button link size="small" @click="clearAllFilters">
            <el-icon><Close /></el-icon>
            清除全部
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 主内容区域 -->
    <div class="content-tabs">
      <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
        <!-- 树形视图 -->
        <el-tab-pane label="树形视图" name="tree">
          <template #label>
            <span class="tab-label">
              <el-icon><Share /></el-icon>
              树形视图
            </span>
          </template>
          
          <el-card shadow="never" class="tree-card">
            <div class="tree-header">
              <div class="tree-info">
                <h3 class="tree-title">权限树结构</h3>
                <el-tag size="small" type="success">{{ getTreeCount() }} 个节点</el-tag>
              </div>
              <div class="tree-actions">
                <el-button size="small" @click="expandAll">
                  <el-icon><Plus /></el-icon>
                  展开全部
                </el-button>
                <el-button size="small" @click="collapseAll">
                  <el-icon><Minus /></el-icon>
                  收起全部
                </el-button>
                <el-button size="small" @click="refreshTree">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
            
            <div class="tree-content" v-loading="treeLoading">
              <el-tree
                ref="permissionTree"
                :data="treeData"
                :props="treeProps"
                node-key="id"
                show-checkbox
                :default-expand-all="false"
                :expand-on-click-node="false"
                :check-on-click-node="false"
                :filter-node-method="filterNode"
                @check-change="handleTreeCheck"
                @node-click="handleNodeClick"
                class="permission-tree"
              >
                <template #default="{ node, data }">
                  <div class="tree-node">
                    <div class="node-content">
                      <el-icon class="node-icon" :class="getNodeIconClass(data)">
                        <component :is="getNodeIcon(data)" />
                      </el-icon>
                      <span class="node-label">{{ data.name }}</span>
                      <el-tag v-if="data.code" size="small" type="info" class="node-code">{{ data.code }}</el-tag>
                    </div>
                    <div class="node-actions">
                      <el-tooltip 
                        :content="data.isSystem ? '系统权限不可编辑' : '编辑'" 
                        placement="top"
                      >
                        <el-button
                          size="small"
                          type="primary"
                          link
                          :disabled="data.isSystem"
                          @click.stop="handleEdit(data)"
                        >
                          <el-icon><Edit /></el-icon>
                        </el-button>
                      </el-tooltip>
                      <el-tooltip content="添加子权限" placement="top">
                        <el-button
                          size="small"
                          type="success"
                          link
                          @click.stop="handleAddChild(data)"
                        >
                          <el-icon><Plus /></el-icon>
                        </el-button>
                      </el-tooltip>
                      <el-tooltip 
                        :content="data.isSystem ? '系统权限不可删除' : '删除'" 
                        placement="top"
                      >
                        <el-button
                          size="small"
                          type="danger"
                          link
                          :disabled="data.isSystem"
                          @click.stop="handleDelete(data)"
                        >
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </el-tooltip>
                    </div>
                  </div>
                </template>
              </el-tree>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 表格视图 -->
        <el-tab-pane label="表格视图" name="table">
          <template #label>
            <span class="tab-label">
              <el-icon><Grid /></el-icon>
              表格视图
            </span>
          </template>
          
          <el-card shadow="never" class="table-card">
            <div class="table-header">
              <div class="table-info">
                <h3 class="table-title">权限列表</h3>
                <div class="table-summary">
                  <el-tag type="primary" size="small">总计 {{ total }}</el-tag>
                  <el-tag type="success" size="small">已选 {{ selectedPermissions.length }}</el-tag>
                </div>
              </div>
              <div class="table-actions">
                <el-button @click="refreshTable">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
            
            <el-table
              ref="permissionTable"
              :data="tableData"
              v-loading="tableLoading"
              row-key="id"
              @selection-change="handleSelectionChange"
              @sort-change="handleSortChange"
              class="permission-table"
              height="500"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column prop="name" label="权限名称" min-width="150" sortable="custom">
                <template #default="{ row }">
                  <div class="permission-name">
                    <el-icon class="permission-icon" :class="getPermissionIconClass(row)">
                      <component :is="getPermissionIcon(row)" />
                    </el-icon>
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column prop="code" label="权限编码" width="200">
                <template #default="{ row }">
                  <el-tag type="info" size="small">{{ row.code }}</el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="status" label="状态" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                    {{ row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  <span>{{ row.remark || row.description || '-' }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="createdAt" label="创建时间" width="160" sortable="custom">
                <template #default="{ row }">
                  <span>{{ formatDate(row.createdAt) }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="updatedAt" label="更新时间" width="160" sortable="custom">
                <template #default="{ row }">
                  <span>{{ formatDate(row.updatedAt) }}</span>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <div class="table-actions-cell">
                    <el-button 
                      size="small" 
                      type="primary" 
                      link 
                      :disabled="row.isSystem"
                      v-if="userStore.hasPermission('permission.update')"
                      @click="handleEdit(row)"
                    >
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button 
                      size="small" 
                      type="success" 
                      link 
                      v-if="userStore.hasPermission('permission.create')"
                      @click="handleAddChild(row)"
                    >
                      <el-icon><Plus /></el-icon>
                      添加子权限
                    </el-button>
                    <el-dropdown @command="(command) => handleDropdownCommand(command, row)">
                      <el-button size="small" link>
                        更多
                        <el-icon><ArrowDown /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item 
                            command="disable" 
                            v-if="row.status === 1 && userStore.hasPermission('permission.status')"
                          >
                            <el-icon><CircleClose /></el-icon>
                            禁用权限
                          </el-dropdown-item>
                          <el-dropdown-item 
                            command="enable" 
                            v-else-if="userStore.hasPermission('permission.status')"
                          >
                            <el-icon><CircleCheck /></el-icon>
                            启用权限
                          </el-dropdown-item>
                          <el-dropdown-item 
                            command="delete" 
                            divided
                            v-if="!row.isSystem && userStore.hasPermission('permission.delete')"
                          >
                            <el-icon><Delete /></el-icon>
                            删除权限
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination">
              <div class="pagination-info">
                <span>显示 {{ (queryParams.page - 1) * queryParams.pageSize + 1 }} 到 {{ Math.min(queryParams.page * queryParams.pageSize, total) }} 条，共 {{ total }} 条记录</span>
              </div>
              <el-pagination
                v-model:current-page="queryParams.page"
                v-model:page-size="queryParams.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 权限编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="permissionForm"
        :model="currentPermission"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="currentPermission.name" placeholder="请输入权限名称" />
        </el-form-item>
        
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="currentPermission.code" placeholder="请输入权限编码" />
        </el-form-item>
        
        <el-form-item label="上级权限" prop="parentId">
          <el-select
            v-model="currentPermission.parentId"
            placeholder="请选择上级权限"
            clearable
            filterable
          >
            <el-option
              v-for="option in parentTreeData"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="currentPermission.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="currentPermission.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { permissionApi } from '@/api/permission'
import { useUserStore } from '@/stores/user'
import {
  Key, Search, Refresh, Delete, Plus, User, UserFilled, Setting, Document,
  Menu, Grid, ArrowUp, ArrowDown, Close, Share, Minus, Edit,
  CircleClose, CircleCheck, Folder
} from '@element-plus/icons-vue'

// 响应式数据
const userStore = useUserStore()
const activeTab = ref('tree')
const showAdvanced = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const treeLoading = ref(false)
const tableLoading = ref(false)
const groupLoading = ref(false)
const selectedPermissions = ref([])
const quickFilters = ref([])
const availableGroups = ref([])

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  code: '',
  status: null,
  dateRange: null,
  sortMin: null,
  sortMax: null,
  includeSystem: true,
  orderBy: 'sort',
  orderDirection: 'asc'
})

// 权限数据
const treeData = ref([])
const tableData = ref([])
const parentTreeData = ref([])
const total = ref(0)

// 当前编辑的权限
const currentPermission = reactive({
  id: null,
  name: '',
  code: '',
  parentId: null,
  status: 1,
  remark: ''
})

// 树形属性配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { pattern: /^[A-Za-z0-9._:-]+$/, message: '权限编码只能包含字母、数字、下划线、点号、冒号', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑权限' : '新增权限')
const isEdit = computed(() => !!currentPermission.id)

// 分组筛选选项 - 现在使用动态加载的availableGroups
const groupFilters = computed(() => 
  availableGroups.value.map(group => ({
    text: group.label,
    value: group.value
  }))
)

// 方法
// 加载顶级权限作为分组选项
const loadAvailableGroups = async () => {
  try {
    groupLoading.value = true
    const response = await permissionApi.getTopLevelPermissions()
    
    if (response.data && response.data.length > 0) {
      availableGroups.value = response.data.map(permission => ({
        label: permission.PermissionName || permission.permissionName || permission.name || '未命名权限',
        value: permission.PermissionCode || permission.permissionCode || permission.code || permission.Id || permission.id,
        icon: getGroupIcon(permission)
      }))
    } else {
      // 如果没有顶级权限，使用默认分组
      availableGroups.value = [
        { label: '用户管理', value: 'user', icon: 'User' },
        { label: '角色管理', value: 'role', icon: 'UserFilled' },
        { label: '系统设置', value: 'system', icon: 'Setting' },
        { label: '日志管理', value: 'log', icon: 'Document' }
      ]
    }
  } catch (error) {
    console.error('加载权限分组失败:', error)
    ElMessage.error('加载权限分组失败')
    // 出错时使用默认分组
    availableGroups.value = [
      { label: '用户管理', value: 'user', icon: 'User' },
      { label: '角色管理', value: 'role', icon: 'UserFilled' },
      { label: '系统设置', value: 'system', icon: 'Setting' },
      { label: '日志管理', value: 'log', icon: 'Document' }
    ]
  } finally {
    groupLoading.value = false
  }
}

// 根据权限获取对应的图标
const getGroupIcon = (permission) => {
  // 统一使用文件夹图标
  return 'Folder'
}

const handleSearch = () => {
  queryParams.page = 1
  if (activeTab.value === 'tree') {
    loadTreeData()
  } else {
    loadTableData()
  }
}

// 刷新所有数据（用于删除等操作后）
const refreshAllData = () => {
  // 刷新当前视图
  handleSearch()
  // 如果当前在表格视图，也预加载树形数据以保持同步
  if (activeTab.value === 'table') {
    loadTreeData()
  }
  // 如果当前在树形视图，也预加载表格数据以保持同步
  if (activeTab.value === 'tree') {
    loadTableData()
  }
}

const resetQuery = () => {
  Object.assign(queryParams, {
    page: 1,
    pageSize: 10,
    name: '',
    code: '',
    group: '',
    status: null,
    dateRange: null,
    sortMin: null,
    sortMax: null,
    includeSystem: true,
    orderBy: 'sort',
    orderDirection: 'asc'
  })
  quickFilters.value = []
  handleSearch()
}

const handleTabChange = (tab) => {
  // 切换标签页时清空选择状态
  selectedPermissions.value = []
  
  if (tab === 'tree') {
    loadTreeData()
  } else {
    loadTableData()
  }
}

// 树形操作
const expandAll = () => {
  const tree = permissionTree.value
  if (tree) {
    const nodes = tree.store._getAllNodes()
    nodes.forEach(node => {
      node.expanded = true
    })
  }
}

const collapseAll = () => {
  const tree = permissionTree.value
  if (tree) {
    const nodes = tree.store._getAllNodes()
    nodes.forEach(node => {
      node.expanded = false
    })
  }
}

const refreshTree = () => {
  loadTreeData()
}

const refreshTable = () => {
  loadTableData()
}

const refreshUserPermissions = () => {
  ElMessage.success('权限已刷新')
  refreshAllData()
}

// 构建树形结构的工具函数
const buildTreeStructure = (permissions) => {
  console.log('开始构建树形结构，权限数据:', permissions)
  
  // 创建一个以ID为键的映射，方便查找
  const permissionMap = new Map()
  permissions.forEach(permission => {
    permissionMap.set(permission.id, { ...permission, children: [] })
  })
  
  const rootNodes = []
  const usedAsChild = new Set() // 记录已经作为子节点的权限
  
  // 构建父子关系
  permissions.forEach(permission => {
    const currentNode = permissionMap.get(permission.id)
    
    if (permission.parentId && permissionMap.has(permission.parentId)) {
      // 检查是否会形成循环引用
      if (!wouldCreateCycle(permission.id, permission.parentId, permissionMap)) {
        // 有父节点且不会形成循环，添加到父节点的children中
        const parentNode = permissionMap.get(permission.parentId)
        parentNode.children.push(currentNode)
        usedAsChild.add(permission.id)
      } else {
        console.warn(`检测到循环引用，权限 ${permission.name} -> ${permissionMap.get(permission.parentId)?.name}`)
        // 如果会形成循环，将其作为根节点
        rootNodes.push(currentNode)
      }
    } else {
      // 没有父节点或父节点不存在，作为根节点
      rootNodes.push(currentNode)
    }
  })
  
  // 如果所有节点都被用作子节点，说明有循环引用，返回所有节点作为根节点
  if (rootNodes.length === 0 && permissions.length > 0) {
    console.warn('所有权限都有父节点但形成循环，将所有权限作为根节点显示')
    return permissions.map(permission => ({ ...permission, children: [] }))
  }
  
  console.log('构建完成，根节点数量:', rootNodes.length)
  console.log('根节点:', rootNodes)
  
  return rootNodes
}

// 检查是否会形成循环引用
const wouldCreateCycle = (childId, parentId, permissionMap, visited = new Set()) => {
  if (visited.has(parentId)) {
    return true // 发现循环
  }
  
  if (parentId === childId) {
    return true // 直接循环
  }
  
  visited.add(parentId)
  
  const parentNode = permissionMap.get(parentId)
  if (parentNode && parentNode.parentId) {
    return wouldCreateCycle(childId, parentNode.parentId, permissionMap, visited)
  }
  
  return false
}

// 加载父级权限选择数据
const loadParentTreeData = async () => {
  try {
    const { permissionApi } = await import('@/api/permission')
    const response = await permissionApi.getPermissionsPaged(0, 1000) // 获取所有权限作为父级选项
    
    console.log('加载父级权限数据:', response)
    
    if (response.data && response.data.permissions) {
      // 转换权限数据，简化为平铺结构，避免循环引用问题
      const allPermissions = response.data.permissions
        .filter(p => p.id !== currentPermission.id) // 排除自己，避免循环引用
        .map(permission => ({
          id: permission.id,
          name: permission.permissionName || permission.PermissionName || '未知权限',
          code: permission.permissionCode || permission.PermissionCode || 'unknown'
        }))
      
      console.log('转换后的父级权限选项:', allPermissions)
      
      // 简化为平铺的选择列表，添加"无上级权限"选项
      parentTreeData.value = [
        {
          id: null,
          name: '无上级权限（根权限）',
          code: 'root'
        },
        ...allPermissions
      ]
      
      console.log('最终的父级权限选择数据:', parentTreeData.value)
    } else {
      console.log('没有获取到权限数据，使用默认选项')
      parentTreeData.value = [{
        id: null,
        name: '无上级权限（根权限）',
        code: 'root'
      }]
    }
  } catch (error) {
    console.error('加载父级权限失败:', error)
    parentTreeData.value = [{
      id: null,
      name: '无上级权限（根权限）',
      code: 'root'
    }]
  }
}
const loadTreeData = async () => {
  treeLoading.value = true
  try {
    // 构建筛选参数
    const filters = {
      name: queryParams.name || undefined,
      code: queryParams.code || undefined,
      group: queryParams.group || undefined,
      status: queryParams.status !== null ? queryParams.status : undefined
    }
    
    // 移除undefined的属性
    Object.keys(filters).forEach(key => {
      if (filters[key] === undefined) {
        delete filters[key]
      }
    })
    
    // 使用真实的权限分页API
    const { permissionApi } = await import('@/api/permission')
    const response = await permissionApi.getPermissionsPaged(0, 100, filters) // 获取所有权限并应用筛选
    
    console.log('权限API返回数据:', response)
    
    if (response.data && response.data.permissions && response.data.permissions.length > 0) {
      // 将真实权限数据转换为树形结构
      const allPermissions = response.data.permissions.map(permission => ({
        id: permission.id,
        name: permission.permissionName || permission.PermissionName || '未知权限',
        code: permission.permissionCode || permission.PermissionCode || 'unknown',
        description: permission.description || permission.Description || '',
        parentId: permission.parentId || permission.ParentId || null,
        type: 'permission',
        status: permission.isActive !== undefined ? (permission.isActive ? 1 : 0) : (permission.IsActive !== undefined ? (permission.IsActive ? 1 : 0) : 1),
        sort: permission.sort || permission.Sort || 1,
        group: permission.group || permission.Group || 'system',
        remark: permission.description || permission.Description || '',
        children: []
      }))
      
      console.log('转换后的权限数据:', allPermissions)
      
      // 构建树形结构
      treeData.value = buildTreeStructure(allPermissions)
      total.value = response.data.totalCount || allPermissions.length
      
      console.log('构建的树形数据:', treeData.value)
    } else {
      console.log('没有权限数据或数据为空')
      treeData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载权限数据失败:', error)
    ElMessage.error('加载权限数据失败')
    treeData.value = []
    total.value = 0
  } finally {
    treeLoading.value = false
  }
}

const loadTableData = async () => {
  tableLoading.value = true
  try {
    // 构建筛选参数
    const filters = {
      name: queryParams.name || undefined,
      code: queryParams.code || undefined,
      group: queryParams.group || undefined,
      status: queryParams.status !== null ? queryParams.status : undefined
    }
    
    // 移除undefined的属性
    Object.keys(filters).forEach(key => {
      if (filters[key] === undefined) {
        delete filters[key]
      }
    })
    
    // 使用真实的权限分页API
    const { permissionApi } = await import('@/api/permission')
    const response = await permissionApi.getPermissionsPaged(
      (queryParams.page - 1), 
      queryParams.pageSize,
      filters
    )
    
    console.log('权限列表API返回数据:', response)
    
    if (response.data && response.data.permissions) {
      // 将真实权限数据转换为表格需要的格式
      console.log('原始权限数据示例:', response.data.permissions[0])
      
      tableData.value = response.data.permissions.map(permission => {
        console.log('处理权限:', permission.permissionName, {
          createdAt: permission.createdAt,
          CreatedAt: permission.CreatedAt,
          updatedAt: permission.updatedAt,
          UpdatedAt: permission.UpdatedAt
        })
        
        return {
          id: permission.id,
          name: permission.permissionName || permission.PermissionName || '未知权限',
          code: permission.permissionCode || permission.PermissionCode || 'unknown',
          description: permission.description || permission.Description || '',
          parentId: permission.parentId || permission.ParentId || null,
          group: permission.group || permission.Group || 'system',
          type: permission.type || permission.Type || 'permission',
          sort: permission.sort || permission.Sort || 1,
          status: permission.isActive !== undefined ? (permission.isActive ? 1 : 0) : (permission.IsActive !== undefined ? (permission.IsActive ? 1 : 0) : 1),
          remark: permission.description || permission.Description || '',
          createdAt: permission.createdAt || permission.CreatedAt || null,
          updatedAt: permission.updatedAt || permission.UpdatedAt || null
        }
      })
      
      total.value = response.data.totalCount || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载权限列表失败:', error)
    ElMessage.error('加载权限列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    tableLoading.value = false
  }
}

// 权限操作
const handleAdd = () => {
  console.log('新增权限：重置表单数据')
  Object.assign(currentPermission, {
    id: null,
    name: '',
    code: '',
    parentId: null,
    group: '',
    type: '',
    sort: 0,
    status: 1,
    remark: ''
  })
  console.log('新增权限：开始加载父级权限数据')
  loadParentTreeData() // 加载父级权限数据
  dialogVisible.value = true
}

const handleEdit = (row) => {
  console.log('编辑权限：', row)
  Object.assign(currentPermission, {
    id: row.id,
    name: row.name,
    code: row.code,
    parentId: row.parentId || null,
    status: row.status || 1,
    remark: row.remark || row.description || ''
  })
  console.log('编辑权限：当前权限数据', currentPermission)
  console.log('编辑权限：开始加载父级权限数据')
  loadParentTreeData() // 加载父级权限数据
  dialogVisible.value = true
}

const handleAddChild = (row) => {
  Object.assign(currentPermission, {
    id: null,
    name: '',
    code: '',
    parentId: row.id,
    status: 1,
    remark: ''
  })
  loadParentTreeData() // 加载父级权限数据
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除权限 "${row.name}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用真实的删除API
    const { permissionApi } = await import('@/api/permission')
    await permissionApi.deletePermission(row.id)
    
    ElMessage.success('权限删除成功')
    refreshAllData()
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除，不做任何处理
      return
    }
    console.error('删除权限失败:', error)
    ElMessage.error(error.message || '删除失败')
  }
}

const handleBatchDelete = async () => {
  if (selectedPermissions.value.length === 0) {
    ElMessage.warning('请选择要删除的权限')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedPermissions.value.length} 个权限吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用真实的批量删除API
    const { permissionApi } = await import('@/api/permission')
    const ids = selectedPermissions.value.map(item => item.id)
    await permissionApi.batchDeletePermissions(ids)
    
    ElMessage.success('权限批量删除成功')
    selectedPermissions.value = []
    refreshAllData()
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除，不做任何处理
      return
    }
    console.error('批量删除权限失败:', error)
    ElMessage.error(error.message || '批量删除失败')
  }
}

const handleSubmit = async () => {
  const form = permissionForm.value
  if (!form) return
  
  try {
    await form.validate()
    submitLoading.value = true
    
    // 使用真实的权限API提交数据
    const { permissionApi } = await import('@/api/permission')
    const permissionData = {
      permissionName: currentPermission.name,
      permissionCode: currentPermission.code || null,
      parentId: currentPermission.parentId || null,
      description: currentPermission.remark || '',
      isActive: currentPermission.status === 1
    }
    
    if (isEdit.value && currentPermission.id) {
      // 更新权限
      const updateData = {
        id: currentPermission.id,
        ...permissionData
      }
      await permissionApi.updatePermission(currentPermission.id, updateData)
      ElMessage.success('权限更新成功')
    } else {
      // 创建新权限
      await permissionApi.createPermission(permissionData)
      ElMessage.success('权限创建成功')
    }
    
    dialogVisible.value = false
    refreshAllData() // 刷新所有数据
    
    // 同时刷新父级权限数据，确保下次编辑时能看到最新的层级关系
    await loadParentTreeData()
  } catch (error) {
    console.error('权限操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDropdownCommand = async (command, row) => {
  try {
    switch (command) {
      case 'disable':
        await handleStatusChange(row, 0)
        break
      case 'enable':
        await handleStatusChange(row, 1)
        break
      case 'delete':
        await handleDelete(row)
        break
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

const handleStatusChange = async (row, status) => {
  try {
    const action = status === 1 ? '启用' : '禁用'
    await ElMessageBox.confirm(
      `确定${action}权限 "${row.name}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: `确定${action}`,
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用更新API来改变状态
    const { permissionApi } = await import('@/api/permission')
    const updateData = {
      id: row.id,
      permissionName: row.name,
      permissionCode: row.code,
      parentId: row.parentId,
      description: row.remark || row.description || '',
      isActive: status === 1
    }
    
    await permissionApi.updatePermission(row.id, updateData)
    ElMessage.success(`权限${action}成功`)
    refreshAllData() // 刷新所有数据
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    console.error('状态更改失败:', error)
    ElMessage.error(error.message || '状态更改失败')
  }
}

// 表格事件
const handleSelectionChange = (selection) => {
  selectedPermissions.value = selection
}

const handleSortChange = ({ prop, order }) => {
  queryParams.orderBy = prop
  queryParams.orderDirection = order === 'ascending' ? 'asc' : 'desc'
  handleSearch()
}

const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.page = 1
  handleSearch()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  handleSearch()
}

// 树形事件
const handleTreeCheck = (data, checked) => {
  // 处理树形选择
  const tree = permissionTree.value
  if (tree) {
    // 获取当前选中的所有节点
    const checkedNodes = tree.getCheckedNodes()
    selectedPermissions.value = checkedNodes
  }
}

const handleNodeClick = (data) => {
  // 处理节点点击
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value) || data.code.includes(value)
}

// 快速筛选
const addQuickFilter = (key, label, type = 'primary') => {
  if (!quickFilters.value.find(f => f.key === key)) {
    quickFilters.value.push({ key, label, type })
  }
}

const removeQuickFilter = (key) => {
  const index = quickFilters.value.findIndex(f => f.key === key)
  if (index > -1) {
    quickFilters.value.splice(index, 1)
    
    // 清除对应的查询参数
    if (key === 'name') queryParams.name = ''
    if (key === 'code') queryParams.code = ''
    if (key === 'group') queryParams.group = ''
    if (key === 'type') queryParams.type = ''
    
    handleSearch()
  }
}

const clearAllFilters = () => {
  quickFilters.value = []
  resetQuery()
}

// 工具函数
const getTreeCount = () => {
  const countNodes = (nodes) => {
    let count = 0
    nodes.forEach(node => {
      count++
      if (node.children && node.children.length > 0) {
        count += countNodes(node.children)
      }
    })
    return count
  }
  return countNodes(treeData.value)
}

const getNodeIcon = (data) => {
  switch (data.type) {
    case 'menu': return Menu
    case 'button': return Grid
    case 'data': return Folder
    default: return Key
  }
}

const getNodeIconClass = (data) => {
  switch (data.type) {
    case 'menu': return 'menu-icon'
    case 'button': return 'button-icon'
    case 'data': return 'data-icon'
    default: return 'default-icon'
  }
}

const getPermissionIcon = (row) => {
  return getNodeIcon(row)
}

const getPermissionIconClass = (row) => {
  return getNodeIconClass(row)
}

const getGroupLabel = (group) => {
  const labels = {
    user: '用户管理',
    role: '角色管理',
    system: '系统设置',
    log: '日志管理'
  }
  return labels[group] || group
}

const getGroupTagType = (group) => {
  const types = {
    user: 'primary',
    role: 'success',
    system: 'warning',
    log: 'info'
  }
  return types[group] || 'default'
}

const getTypeLabel = (type) => {
  const labels = {
    menu: '菜单权限',
    button: '按钮权限',
    data: '数据权限'
  }
  return labels[type] || type
}

const getTypeTagType = (type) => {
  const types = {
    menu: 'primary',
    button: 'success',
    data: 'warning'
  }
  return types[type] || 'default'
}

const filterGroup = (value, row) => {
  return row.group === value
}

const formatDate = (date) => {
  if (!date) return '-'
  
  try {
    console.log('格式化日期:', date, typeof date)
    
    // 如果已经是格式化的字符串，直接返回
    if (typeof date === 'string' && (date.includes('/') || date.includes('-'))) {
      // 尝试解析现有的日期字符串
      const parsedDate = new Date(date)
      if (!isNaN(parsedDate.getTime())) {
        return parsedDate.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
      }
      return date
    }
    
    // 如果是ISO字符串或Date对象，格式化
    const dateObj = new Date(date)
    if (isNaN(dateObj.getTime())) {
      console.warn('无效的日期:', date)
      return '-'
    }
    
    return dateObj.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化失败:', error, '原始数据:', date)
    return '-'
  }
}

// 组件引用
const permissionTree = ref()
const permissionTable = ref()
const permissionForm = ref()

// 初始化
onMounted(() => {
  loadAvailableGroups()
  loadTreeData()
})
</script>

<style scoped>
.permissions-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.title-section h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
}

.page-description {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
  line-height: 1.5;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions :deep(.el-button) {
  color: white;
  border-color: rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.header-actions :deep(.el-button:hover) {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.search-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-stats {
  font-size: 14px;
  color: #909399;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.form-item {
  margin-bottom: 16px;
}

.form-item :deep(.el-input),
.form-item :deep(.el-select) {
  width: 200px;
}

.button-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 高级搜索 */
.advanced-search {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.range-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: #909399;
}

/* 快速筛选 */
.quick-filters {
  margin-top: 16px;
  padding: 12px 0;
  border-top: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.filter-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* 内容标签页 */
.content-tabs {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 树形卡片 */
.tree-card,
.table-card {
  border: none;
  box-shadow: none;
}

.tree-header,
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.tree-info,
.table-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tree-title,
.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.table-summary {
  display: flex;
  gap: 8px;
}

.tree-actions,
.table-actions {
  display: flex;
  gap: 8px;
}

/* 树形组件 */
.tree-content {
  min-height: 400px;
}

.permission-tree {
  background: white;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.tree-node:hover {
  background: #f5f7fa;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-icon {
  font-size: 16px;
}

.node-icon.menu-icon {
  color: #409eff;
}

.node-icon.button-icon {
  color: #67c23a;
}

.node-icon.data-icon {
  color: #e6a23c;
}

.node-icon.default-icon {
  color: #909399;
}

.node-label {
  font-size: 14px;
  color: #303133;
}

.node-code {
  margin-left: 8px;
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

/* 表格组件 */
.permission-table {
  margin-bottom: 20px;
}

.permission-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-icon {
  font-size: 16px;
}

.permission-icon.menu-icon {
  color: #409eff;
}

.permission-icon.button-icon {
  color: #67c23a;
}

.permission-icon.data-icon {
  color: #e6a23c;
}

.permission-icon.default-icon {
  color: #909399;
}

.table-actions-cell {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

/* 对话框 */
.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .permissions-container {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }

  .search-form {
    flex-direction: column;
  }

  .form-item :deep(.el-input),
  .form-item :deep(.el-select) {
    width: 100%;
  }

  .tree-header,
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .pagination {
    flex-direction: column;
    gap: 16px;
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-tabs__item) {
  font-weight: 500;
}

:deep(.el-tabs__active-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.el-table th.el-table__cell) {
  background: #f8f9fa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.el-tree-node__content) {
  padding: 8px 0;
}

:deep(.el-tree-node__content:hover) {
  background: transparent;
}

:deep(.el-dropdown-menu) {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}
</style>
